import requests
import json

# 获取课程列表
def fetch_courses(api_url):
    try:
        response = requests.get(api_url + '?pageNum=1&pageSize=100&teacher=1')
        response.raise_for_status()  # 如果响应状态码不是200，会抛出异常
        resp = response.json() 
        print(resp['data']['records'])
        return resp['data']['records']
    except requests.exceptions.RequestException as e:
        print(f"请求错误: {e}")
        return []
    
# 获取学生列表
def fetch_students(api_url,courseId):
    try:
        response = requests.get(api_url + '?pageNum=1&pageSize=300&courseId=' + courseId)
        response.raise_for_status()  # 如果响应状态码不是200，会抛出异常
        resp = response.json()  
        print(resp['data']['records'])
        return resp['data']['records']
    except requests.exceptions.RequestException as e:
        print(f"请求错误: {e}")
        return []
    
# 提交考勤
def add_attendance(api_url, student):
    headers = {"Content-Type":"application/json; charset=utf8"}
    try:
        response = requests.post(api_url, data=json.dumps(student), headers=headers)
        response.raise_for_status()  # 如果响应状态码不是200，会抛出异常
        # 解析并返回响应内容
        resp = response.json()
        if resp.get('success', False):
            return resp.get('message', '考勤提交成功')
        else:
            return f"考勤提交失败: {resp.get('message', '未知错误')}"
    except requests.exceptions.RequestException as e:
        print(f"请求错误: {e}")
        return f"请求错误: {str(e)}"